<template>
	<view>
		<view class="wayBox" v-if="!isType">
			<u-tabs
				:list="list"
				lineWidth="30"
				lineColor="#f56c6c"
				:current="currentNum"
				:activeStyle="{
					color: '#303133',
					fontWeight: 'bold',
					transform: 'scale(1.05)'
				}"
				:inactiveStyle="{
					color: '#606266',
					transform: 'scale(1)'
				}"
				itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;"
				@change="changeTabs"
			></u-tabs>
		</view>

		<!-- 提交订单 -->
		<view class="submitOrder-main">
			<!-- 订单详情 -->
			<view class="orderInfo">
				<!-- 送货上门 -->
				<view class="homeDelivery" v-if="currentNum == 0">
					<view class="site" @click="openAddress">
						<view class="site-input">
							<input type="text" class="inputSty" placeholder="请选择收货地址" disabled :value="addressInfo.address" />
						</view>
						<view class="site-icon">
							<uni-icons type="forward" size="20"></uni-icons>
						</view>
					</view>

					<view class="distribution">
						<view class="distribution-left">
							<uni-tag text="配送方式" size="mini" style="margin-right: 8rpx" type="error"></uni-tag>
							<text>{{isType?'快递配送':'骑手配送'}}</text>
						</view>

						<view class="distribution-right">预计3天送达</view>
					</view>
				</view>

				<!-- 到店自提 -->
				<view class="pickUpAtTheStore" v-else>
					<view class="siteInfo">
						<view class="site">
							<uni-tag text="自提点" size="mini" style="margin-right: 8rpx" type="error"></uni-tag>
							<text>
								{{ storeInfo.address || '暂无信息' }}
							</text>
						</view>
						<view class="map">
							<map name="shopMap" style="width: 100%; height: 100%" :longitude="storeInfo.lng" :latitude="storeInfo.lat"></map>
						</view>
					</view>

					<view class="times">
						<view class="times-left">
							<text class="times-title">自提时间</text>
							<view class="time">09/19 11:00-12:00</view>
						</view>
						<view class="times-right">
							<text class="times-title">预留电话</text>
							<view class="time">
								{{ addressInfo.phone }}
							</view>
						</view>
					</view>
				</view>

				<view class="orderInfos" v-for="(item, index) in cloudOrderPreviewList" :key="index">
					<view class="orderInfo-shop">
						<text>{{ item.store_name }}</text>
						<uni-icons type="forward" size="18"></uni-icons>
					</view>
					<view class="orderInfo-shopData" v-for="(jitem, jindex) in item.goods" :key="jitem.id">
						<view class="shopimage">
							<image :src="imageUrls(jitem.fileUrl)" class="images"></image>
						</view>
						<view class="shopinfo">
							<view class="shopinfo-title">
								<text class="title">{{ jitem.name }}</text>
								<text class="pir">¥{{ jitem.price != '0.00' ? jitem.price : jitem.saleprice.toFixed(2) }}</text>
							</view>
							<view class="shopinfo-gg">
								<text>规格:{{ jitem.spec }}</text>
								<text>x{{ jitem.buy_num }}</text>
							</view>
							<view class="shopinfo-tags">
								<uni-tag :text="jitem.mediaName" size="mini" style="margin-right: 8rpx" type="error"></uni-tag>
							</view>
						</view>
					</view>
					<view class="shop-ps" v-if="currentNum == 0">
						<view class="">配送费</view>
						<view class="ps">
							{{ item.freight_price == '0.00' ? '免运费' : '+￥' + item.freight_price }}
						</view>
					</view>
					<view class="shop-ps">
						<view class="">优惠券</view>
						<view class="ps" @click="opencouponShow(item, index)" style="color: #999; display: flex; align-items: center">
							<text v-if="!item.shopCouponInfo">选择优惠券</text>
							<text v-else style="color: #e43927">-￥{{ item.shopCouponInfo.price }}</text>
							<uni-icons type="right" size="20" color="#999"></uni-icons>
						</view>
					</view>
					<view class="shop-xj">
						<view class="title">
							小计
							<text style="font-size: 24rpx; color: #999">（不包含配送费）</text>
						</view>
						<view class="pir">
							<text style="color: #e43927">
								<text style="font-size: 12px">￥</text>
								{{ item.total_pay_money }}
							</text>
							<text v-if="item.shopCouponInfo" style="margin-left: 10rpx; font-size: 12px; text-decoration: line-through; color: #999">
								原价：￥{{ item.total_price }}
							</text>
						</view>
					</view>
				</view>

				<view class="tips">
					<view class="tips-title">备注</view>
					<view class="tips-input">
						<input type="text" placeholder="推荐使用无接触配送" style="text-align: right; font-size: 26rpx" />
					</view>
				</view>
			</view>
		</view>

		<!-- 订单提交 -->
		<view class="addAddress-btn" :style="bottomStyle">
			<text style="margin-right: 30rpx; flex: 1">
				合计：￥
				<text style="font-size: 36rpx; font-weight: bold">{{ include_freight_total_price }}</text>
			</text>
			<view class="btn" @click="submitOrder">提交订单</view>
		</view>

		<u-popup :show="show" @close="getClose" closeable :round="10">
			<view class="addressHeader">地址列表</view>
			<u-radio-group v-model="checkboxValue" shape="circle">
				<view class="addressList">
					<view class="addRessItem" v-for="(item, index) in addressListData" :key="item.id">
						<view class="addRessInfo-change">
							<u-radio activeColor="#e43927" label=" " :name="item.id"></u-radio>
						</view>
						<view class="addRessInfo">
							<view class="addRessInfo_hedaer">{{ item.name }} {{ item.phone }}</view>
							<view class="addRessInfos">
								{{ item.address }}
							</view>
						</view>
					</view>
				</view>
			</u-radio-group>

			<view class="addRessBtn">
				<view class="btn" @click="changeAddress">切换地址</view>
			</view>
		</u-popup>

		<u-popup :show="couponShow" @close="getCouponClose" closeable :round="10">
			<view class="addressHeader">优惠券列表</view>
				<view class="addressList" v-if="couponList.length > 0">
					<view class="addRessItem" v-for="(item, index) in couponList" :key="item.id" @click="groupChange(item.id)">
						<view class="addRessInfo-change">
							<uni-icons type="checkbox-filled" size="20" color="#e43927" v-if="couponCheckboxValue == item.id"></uni-icons>
							<uni-icons type="circle" size="20" v-else color="#444"></uni-icons>
						</view>
						<view class="addRessInfo">
							<view class="addRessInfo_hedaer">{{ item.name }}</view>
							<view class="addRessInfos">满{{ item.full }}减{{ item.price }}</view>
						</view>
					</view>
				</view>
			<u-empty mode="list" v-else icon="http://cdn.uviewui.com/uview/empty/list.png" text="暂无满足优惠条件的券~"></u-empty>

			<view class="addRessBtn">
				<view class="btn" @click="setUpCoupon">确认选择</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { cloudOrderPreview, cloudCreateOrder } from '../../api/order/index.js';
import { userAddressList, cloudDelCart, userMyCoupon } from '../../api/home/index.js';
import { imageUrl } from '../../utils/tools.js';
import { flashOrderPreview, flashdetail, flashcreateOrder } from '../../api/flash/index.js';
export default {
	data() {
		return {
			// 地址列表数据
			addressListData: [],
			// 订单详细数据
			cloudOrderPreviewList: null,
			// 总计
			include_freight_total_price: 0,
			// 地址
			addressInfo: null,
			// 全国或者闪电
			isType: true,
			// 订单会话记录
			session: '',
			list: [
				{
					name: '外卖配送'
				},
				{
					name: '到店自提'
				}
			],
			currentNum: 0,
			storeInfo: null,
			show: false,
			checkboxValue: '',
			typeName: '',

			couponShow: false,
			couponCheckboxValue: '',
			couponList: [],

			shopIndex: '',
			couponInfo: {}
		};
	},

	computed: {
		bottomStyle() {
			const systemInfo = uni.getSystemInfoSync();
			const { safeAreaInsets } = systemInfo;
			const bottomSafeAreaHeight = safeAreaInsets.bottom || 0;
			return `padding-bottom: ${bottomSafeAreaHeight ? bottomSafeAreaHeight + 'px' : '20rpx'}`;
		}
	},

	async onLoad(option) {
		const { type } = option;
		if (type == '0') {
			this.isType = true;
		} else {
			this.isType = false;
		}

		this.typeName = type;
	},

	async onShow() {
		await this.getUserAddressList();
		if (this.addressListData.length > 0) {
			const addressInfo = this.addressListData.find((item) => item.default == '1');
			this.addressInfo = addressInfo || this.addressListData[0];
			this.checkboxValue = this.addressInfo.id;
			if (this.typeName == '0') {
				await this.getCloudOrderPreview(this.addressInfo.id);
			} else {
				await this.getflashOrderPreview(this.addressInfo.id);
			}
		} else {
			uni.navigateTo({
				url: '/pages/addAddress/addAddress'
			});
		}
	},

	methods: {
		async submitOrder() {
			if (this.isType) {
				await this.gotocheckstand();
			} else {
				await this.getflashcreateOrder();
			}
		},

		// 图片路径拼接
		imageUrls(fileUrl) {
			return imageUrl(fileUrl);
		},

		// 全国送 - 提交订单
		async gotocheckstand() {
			await this.getDeleteOrder();
			try {
				const resData = await cloudCreateOrder({
					session: this.session
				});
				uni.showToast({
					title: '提交成功',
					icon: 'none'
				});
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/order/order?id=0'
					});
				}, 500);
			} catch (e) {
				throw Error(e);
			}
		},

		// 闪电送 - 提交订单
		async getflashcreateOrder() {
			await this.getDeleteOrder();
			try {
				const resData = await flashcreateOrder({
					session: this.session
				});
				uni.showToast({
					title: '提交成功',
					icon: 'none'
				});
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/order/order?id=0'
					});
				}, 500);
			} catch (e) {
				throw Error(e);
			}
		},

		//  删除商品
		async getDeleteOrder(id) {
			let cartShopList = this.$store.state.cartShopList || [];
			let ids = [];
			cartShopList.forEach((item) => {
				ids.push(item.card_id);
			});

			try {
				const resData = await cloudDelCart({
					ids,
					type: this.currentNum
				});
			} catch (e) {
				throw Error(e);
			}
		},

		// 切换全国送or闪电送
		async changeTabs(tagsInfo) {
			this.currentNum = tagsInfo.index;
			await this.getflashOrderPreview(this.addressInfo.id);
			if (tagsInfo.index == 1) {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						this.getflashdetail(res);
					},
					fail: function (err) {
						console.error('获取位置信息失败：', err);
					}
				});
			}
		},

		// 门店信息
		async getflashdetail(res) {
			for (let key in this.cloudOrderPreviewList) {
				try {
					const query = {
						lng: res.longitude,
						lat: res.latitude,
						id: this.cloudOrderPreviewList[key].store.id
					};
					const resData = await flashdetail(query);
					this.storeInfo = resData.data;
				} catch (e) {
					throw Error(e);
				}
			}
		},

		// 获取地址列表
		async getUserAddressList() {
			try {
				const resData = await userAddressList();
				this.addressListData = resData.data;
			} catch (e) {
				throw Error(e);
			}
		},

		// 全国送 - 订单预览
		async getCloudOrderPreview(id, couponInfo) {
			try {
				let cartShopList = this.$store.state.cartShopList || [];
				let queryData = [];
				cartShopList.forEach((item) => {
					queryData.push({
						goods_id: item.id,
						num: item.num,
						card_id: item.card_id || ''
					});
				});

				let query = {
					goods: queryData,
					address_id: id
				};

				if (couponInfo) {
					query.coupon = couponInfo;
				}

				const resData = await cloudOrderPreview(query);
				this.session = resData.data.session;
				this.cloudOrderPreviewList = resData.data.store;
				this.include_freight_total_price = resData.data.pay_money;
			} catch (e) {
				throw Error(e);
			}
		},

		// 闪电送 - 订单预览
		async getflashOrderPreview(id, couponInfo) {
			try {
				let cartShopList = this.$store.state.cartShopList || [];
				let queryData = [];
				cartShopList.forEach((item) => {
					queryData.push({
						goods_id: item.id,
						num: item.num,
						card_id: item.card_id || ''
					});
				});

				let query = {
					goods: queryData,
					address_id: id,
					is_pick: this.currentNum
				};

				if (couponInfo) {
					query.coupon = couponInfo;
				}

				const resData = await flashOrderPreview(query);
				this.session = resData.data.session;
				this.cloudOrderPreviewList = resData.data.store;
				this.include_freight_total_price = resData.data.pay_money;
			} catch (e) {
				throw Error(e);
			}
		},

		// 打开地址列表
		openAddress() {
			this.show = true;
		},

		getClose() {
			this.show = false;
		},

		// 切换地址
		async changeAddress() {
			const addressInfo = this.addressListData.filter((item) => {
				return item.id == this.checkboxValue;
			});
			this.addressInfo = addressInfo[0];
			this.getClose();
			if (this.typeName == '0') {
				await this.getCloudOrderPreview(this.addressInfo.id);
			} else {
				await this.getflashOrderPreview(this.addressInfo.id);
			}
		},

		opencouponShow(info, index) {
			this.shopIndex = index;
			this.storeInfo = info;
			this.getuserCouponList();
		},

		getCouponClose() {
			this.couponShow = false;
		},

		// 获取卡券
		async getuserCouponList() {
			const resData = await userMyCoupon({
				status: 0
			});
			const couponList = resData.data;

			couponList.forEach((item) => {
				if (!item.store.id) {
					item.store.id = 0;
				}
			});

			this.couponList = couponList.filter((item) => {
				return item.store.id == this.storeInfo.store_id && Number(item.full) <= Number(this.storeInfo.total_price);
			});
			this.couponShow = true;
		},

		// 确认选择优惠券
		async setUpCoupon() {
			const couponCheckboxValue = this.couponCheckboxValue;
			this.couponInfo[this.storeInfo.store_id] = couponCheckboxValue;
			const shopCouponInfo = this.couponList.filter((item) => {
				return (item.id = couponCheckboxValue);
			});
			if (this.typeName == '0') {
				await this.getCloudOrderPreview(this.addressInfo.id, this.couponInfo);
			} else {
				await this.getflashOrderPreview(this.addressInfo.id, this.couponInfo);
			}
			await this.getuserCouponList();
			this.cloudOrderPreviewList[this.shopIndex].shopCouponInfo = shopCouponInfo[0];
			this.couponShow = false;
		},
		
		groupChange(id){
			this.couponCheckboxValue = id;
		}
	}
};
</script>

<style scoped lang="scss">
.wayBox {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 80rpx;
}
.submitOrder-main {
	box-sizing: border-box;
	padding: 20rpx;
	padding-bottom: 200rpx;
	.orderInfo {
		font-size: 26rpx;
		.homeDelivery {
			box-sizing: border-box;
			padding: 10rpx 30rpx;
			background-color: #fff;
			border-radius: 24rpx;
			.site {
				display: flex;
				align-items: center;
				border-bottom: 1px #f3f3f3 solid;
				padding: 20rpx 0px;
				height: 50rpx;
				.site-input {
					flex: 1;
					.inputSty {
						font-size: 26rpx;
					}
				}
				.site-icon {
					width: 50rpx;
					height: 50rpx;
					line-height: 50rpx;
					text-align: center;
				}
			}

			.distribution {
				display: flex;
				align-items: center;
				padding: 20rpx 0px;
				justify-content: space-between;
				height: 50rpx;
				.distribution-left {
					display: flex;
					align-items: center;
				}

				.distribution-right {
					color: #f9ae3d;
				}
			}
		}

		.pickUpAtTheStore {
			box-sizing: border-box;
			padding: 20rpx 30rpx;
			margin-bottom: 20rpx;
			background-color: #fff;
			border-radius: 24rpx;
			.siteInfo {
				display: flex;
				height: 140rpx;
				padding-top: 10rpx;
				border-bottom: 1px #f3f3f3 solid;
				.site {
					flex: 1;
					font-weight: bold;
					font-size: 24rpx;
					margin-right: 10rpx;
					line-height: 1.8;
				}

				.map {
					width: 240rpx;
					height: 100%;
					background-color: #f3f3f3;
				}
			}

			.times {
				display: flex;
				padding-top: 20rpx;
				height: 100rpx;
				.times-left {
					flex: 1;
					border-right: 1px #f3f3f3 solid;
					.times-title {
						font-size: 28rpx;
						color: #999;
					}
					.time {
						padding-top: 8rpx;
						font-size: 30rpx;
					}
				}

				.times-right {
					flex: 1;
					box-sizing: border-box;
					padding: 0px 30rpx;
					.times-title {
						font-size: 28rpx;
						color: #999;
					}
					.time {
						padding-top: 8rpx;
						font-size: 30rpx;
					}
				}
			}
		}

		.orderInfos {
			box-sizing: border-box;
			padding: 20rpx;
			background-color: #fff;
			border-radius: 24rpx;
			margin-top: 20rpx;
			.orderInfo-shop {
				display: flex;
				align-items: center;
				font-size: 26rpx;
				height: 60rpx;
				padding-bottom: 10rpx;
				border-bottom: 1px #f3f3f3 solid;
			}

			.orderInfo-shopData {
				display: flex;
				box-sizing: border-box;
				padding: 20rpx 0px;
				padding-bottom: 10rpx;
				border-bottom: 1px #f3f3f3 solid;
				.shopimage {
					width: 180rpx;
					height: 180rpx;
					.images {
						width: 160rpx;
						height: 160rpx;
					}
				}
				.shopinfo {
					flex: 1;
					.shopinfo-title {
						display: flex;
						font-weight: bold;
						justify-content: space-between;
						.title {
							font-size: 26rpx;
							margin-right: 5px;
						}
					}

					.shopinfo-gg {
						display: flex;
						justify-content: space-between;
						margin: 15rpx 0px;
						font-size: 26rpx;
						color: #999;
					}
				}
			}

			.shop-ps {
				display: flex;
				justify-content: space-between;
				height: 50rpx;
				line-height: 50rpx;
				padding: 20rpx 0;
				border-bottom: 1px #f3f3f3 solid;
				font-size: 28rpx;
				.ps {
					color: red;
				}
			}

			.shop-xj {
				display: flex;
				justify-content: space-between;
				height: 70rpx;
				line-height: 70rpx;
				padding: 20rpx 0;
				padding-bottom: 0px;
				.title {
					font-size: 32rpx;
				}
				.pir {
					font-size: 36rpx;
				}
			}
		}

		.tips {
			display: flex;
			align-items: center;
			justify-content: space-between;
			box-sizing: border-box;
			padding: 20rpx;
			border-radius: 24rpx;
			background-color: #fff;
			margin-top: 20rpx;
			font-size: 26rpx;
		}
	}
}

.addAddress-btn {
	position: fixed;
	bottom: 0rpx;
	left: 0px;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: space-between;
	box-sizing: border-box;
	padding: 0px 20rpx;
	padding-top: 20rpx;
	background-color: #fff;
	z-index: 999;
	.btn {
		width: 280rpx;
		height: 80rpx;
		border-radius: 80rpx;
		background-color: #e43927;
		color: #fff;
		text-align: center;
		line-height: 80rpx;
		font-size: 28rpx;
	}
}

.addressHeader {
	height: 80rpx;
	line-height: 80rpx;
	font-size: 30rpx;
	font-weight: bold;
	text-align: center;
	color: #444;
	border-bottom: 1px #f3f3f3 solid;
	background-color: #fff;
}

.addressList {
	height: 40vh;
	width: 100%;
	box-sizing: border-box;
	padding: 20rpx;
	overflow-y: scroll;
	display: flex;
	flex-direction: column;
	background-color: #fff;
	.addRessItem {
		width: 100%;
		padding-bottom: 20rpx;
		border-bottom: 1px #f3f3f3 solid;
		font-size: 26rpx;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
		.addRessInfo-change {
			margin-right: 20rpx;
		}

		.addRessInfo {
			.addRessInfo_hedaer {
				margin-bottom: 10rpx;
			}

			.addRessInfos {
				color: #999;
			}
		}
	}
}

.addRessBtn {
	background-color: #fff;
	box-sizing: border-box;
	padding: 20rpx;
	padding-bottom: 0px;
	.btn {
		background-color: #e43927;
		color: #fff;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 10rpx;
	}
}
</style>
